package com.example.curator.leader;

import com.example.curator.CuratorClientUtils;
import com.google.common.collect.Lists;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.recipes.leader.LeaderLatch;
import org.apache.curator.framework.recipes.leader.LeaderLatchListener;

import java.util.List;

public class LeaderLatchDemo {
    protected static String PATH = "/francis/leader";
    private static final int CLIENT_QTY = 10;


    public static void main(String[] args) throws Exception {
        List<CuratorFramework> clients = Lists.newArrayList();
        List<LeaderLatch> examples = Lists.newArrayList();
        for (int i = 0; i < CLIENT_QTY; i++) {
            CuratorFramework client = CuratorClientUtils.getInstance();
            clients.add(client);

            LeaderLatch latch = new LeaderLatch(client, PATH, "Client #" + i);
            int finalI = i;
            latch.addListener(new LeaderLatchListener() {

                @Override
                public void isLeader( ) {
                    // TODO Auto-generated method stub
                    System.out.println("I am Leader" + finalI);
                }

                @Override
                public void notLeader( ) {
                    // TODO Auto-generated method stub
                    System.out.println("I am not Leader" + finalI);
                }
            });
            examples.add(latch);
            latch.start();
        }
        Thread.sleep(10000);
        LeaderLatch currentLeader = null;
        for (LeaderLatch latch : examples) {
            if (latch.hasLeadership()) {
                currentLeader = latch;
            }
        }
        System.out.println("current leader is " + currentLeader.getId());
        System.out.println("release the leader " + currentLeader.getId());
        currentLeader.close();

        Thread.sleep(5000);

        for (LeaderLatch latch : examples) {
            if (latch.hasLeadership()) {
                currentLeader = latch;
            }
        }
        System.out.println("current leader is " + currentLeader.getId());
        System.out.println("release the leader " + currentLeader.getId());

    }
}